<template>
  <el-row :gutter="5">
    <el-col :xl="{span: 6, offset: 9}" :lg="{span: 8, offset: 8}" :md="{span: 10, offset: 7}"
            :sm="{span: 12, offset: 6}"
            :xs="{span: 20, offset: 2}" style="margin-top: 15%;">
      <el-card>
        <div slot="header" class="clearfix">
          <span>登录</span>
        </div>
        <el-alert
          v-if="this.msg !== ''"
          :title="this.msg"
          type="error">
        </el-alert>
        <el-alert
          v-if="this.ok"
          title="登录成功，正在返回首页"
          type="success">
        </el-alert>
        <el-form :model="luser" class="bd">
          <el-form-item label="用户名">
            <el-input v-model="luser.username" class="lg" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="luser.password" class="lg" placeholder="请输入密码" show-password
                      @keyup.enter.native="login"></el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: center; padding-top: 20px;">
          <el-button type="primary" @click="login">登录</el-button>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
  import md5 from 'js-md5';
  import axios from 'axios'
  let _c = require('~/assets/config')

  export default {
    async asyncData({req, redirect, $axios}) {
      let opt = {};
      let _h = _c.API_HOST;
      if (process.server) {
        opt.headers = {
          "Cookie": req.headers.cookie + ";"
        };
      } else {
        $axios.defaults.withCredentials = true;
      }
      let {user} = await $axios.$get(`${_h}/user/islogin`, opt);
      if (user !== undefined && user !== null) {
        redirect('/')
      }
      return {
        luser: {
          username: '',
          password: ''
        },
        msg: '',
        ok: false
      }
    },
    methods: {
      login: function () {
        axios.defaults.withCredentials = true;
        let _h = _c.API_HOST;
        let _v = this;
        axios.post(`${_h}/user/login`, {
          "username": _v.luser.username,
          "password": md5(_v.luser.password)
        }).then((res) => {
          let _d = res.data;
          if (_d.id === -3) {
            _v.$router.push({path: '/'});
          } else if (_d.id === 10) {
            _v.$router.push({path: '/change_password'});
          } else if (_d.id === -1) {
            _v.msg = '用户名或密码错误';
          } else if (_d.id === -100) {
            _v.msg = '参数错误';
          } else if (_d.id === 1) {
            _v.msg = '';
            _v.ok = true;
            setTimeout(function(){_v.$router.push({path: '/'})}, 3000);
          }
        })
      }
    }
  }
</script>

<style>
  .bd {
    padding-left: 3%;
    padding-right: 3%;
    text-align: right;
  }

  .lg {
    margin-left: auto;
    margin-right: auto;
  }

  .lgp {
    display: block;
    padding-top: 20px;
  }
</style>
